// 主界面
;
define(function(require, exports, module) {
	'use strict';
	var util = require("util");
	var base = require("base");
	var leftMenu = require("../leftMenu/leftMenu");
	var topMenu = require("../topMenu/topMenu");
	var router = require("../hash/pageRouter");
	var css_loanNotice = require("./loanNotice.css");
	var dialog = require("dialog");
	var validate = require("validate");
	var databind = require("databind");
	var constant = require("constant");
	var tools = require("tools");
	var footer = require("../footer/footer_main");
	var js_loanNoticeList = require("./loanNoticeList.js");
	var pageIndex = 1,
		pageSize = 5,
		totalPageCount = 1,
		totalRecordCount = 0; //分页初始化
	var imgSrc;
	var financeId;
	var recieveNoticeId;
	var financeNumber;
	var totalLoanAmount;
	var fileUuid;
	var financeId;
	var loanNoticeId;
	var left;
	var financeAmount;
	var enterpriseId;
	var type;
	var init = function(page) {
		financeId = page.params.financeId || base.getUrlParam("financeId");
		loanNoticeId = page.params.loanNoticeId || base.getUrlParam("loanNoticeId");
		
		$(".multistageAudit").append("<input type='hidden' name='loanNoticeId' value='" + loanNoticeId + "' />");
		type = page.params.type || base.getUrlParam("type");
		footer.init();
		$("#footer").removeClass("none");
		leftMenu.init(5);
		topMenu.init(1);
		$(".footer").removeClass("none");
		$(".table-section").removeClass("none");
		$("#leftMenu6").find(".leftMenu-item").removeClass("leftMenu-active");
		$("#leftMenu6 .leftMenu li:first-child").addClass("leftMenu-open");
		$(".loanNoticeList").addClass("leftMenu-active");
		inquireLoanNoticeDetail();
		initEvent();
		router.init();
		js_loanNoticeList.init();
		inquireCurrentOperationList();
	};
	var initEvent = function() {
		//若未登录，则返回登陆页面
		if (base.getData("sid") == null || base.getData("sid") == "" || base.getData("sid") == undefined) {
			top.location.href = "../login/login.html";
		}
		//点击首页
		$(".loanNoticeList").unbind("click").click(function() {
			top.location.href = "../financing/loanNoticeList.html";
		});
		
		//查看审批记录
		$("#loanNotice .auditRecord").unbind("click").click(function(){
			window.open("../auditRecord/auditRecord.html?recordType=2,1&recordId=" + loanNoticeId + "," + financeId);
		});

		//审核同意
		$("#loanNotice .agree").on("click", function() {
			databind.submitDom($(".loanNoticeContent"), function(data) {
				base.alert(1, "收款记录审核成功");
				top.location.href = "../financing/loanNoticeList.html";
			});
		});
		
		//审核拒绝
		$("#loanNotice .oppose").on("click", function() {
			dialog.showConfirmDialog("审核拒绝", "确定拒绝该笔放款申请吗？", function(){
				opposeLoanNotice();
			});
		});
		
		$("#loanNotice .print").unbind("click").click(function(){
			tools.printit($("#loanNotice"),'preview');
		});
		
		//多级审核保存
		$(".button-Save").unbind("click").click(function(){
			$(".multistageAudit").attr("action", "saveLoanNoticeAudit");
			$(this).parents(".multistageAudit").append('<input type="hidden" name="autoNotice" value="'+$("#loanNotice select[name=autoNotice]").val()+'" />');
			databind.submitDom($(this).parents(".multistageAudit"), function(){
				base.alert(1, "保存成功！");
				router.route("financing/loanNotice.html?loanNoticeId=" + loanNoticeId + "&type=approve");
			});
		});
		
		//多级审核提交
		$(".button-Submit").unbind("click").click(function(){
			$(".multistageAudit").attr("action", "submitLoanNoticeAudit");
			$(this).parents(".multistageAudit").append('<input type="hidden" name="autoNotice" value="'+$("#loanNotice select[name=autoNotice]").val()+'" />');
			databind.submitDom($(this).parents(".multistageAudit"), function(){
				base.alert(1, "提交成功！");
				location.href = "../financing/loanNoticeList.html";
//				router.route("financing/loanNotice.html?loanNoticeId=" + loanNoticeId + "&type=approve");
			});
		});
	};
	
	//查询放款详情
	var inquireLoanNoticeDetail = function() {
		base.fnAjax({
			action: "inquireLoanNoticeDetail.json",
			oData: {
				loanNoticeId: loanNoticeId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
//					if (data.datas[0].productType == 5) {
//						$("span[name=enterpriseName]").attr("name", "beneficiaryName");
//					}
					
					databind.fillForm($(".loanNoticeContent"), data.datas[0]);
					juicer.register("getValueByKey", constant.getValueByKey);
					juicer.register("formatCurrency", tools.formatCurrency);
					juicer.register("inquireFile", tools.inquireFile);
					
					if (data.datas[0].productType == 3 || data.datas[0].productType == 5 || data.datas[0].productType == 6) {
						$(".loan_tr").remove();
						var tpl = $("#bulkstockLoanNoticeTpl1").html();
						var html = juicer(tpl, data.datas[0]);
						$("#bulkstockLoanNoticeListBody").html(html);
					} else {
						$(".loan_tr1").remove();
						var tpl = $("#bulkstockLoanNoticeTpl").html();
						var html = juicer(tpl, data.datas[0]);
						$("#bulkstockLoanNoticeListBody").html(html);
					}
					
					var tpl1 = $("#loanNotice .financeFilesNormListTpl").html();
					var html1 = juicer(tpl1, data);
					$("#loanNotice .financeFilesNormList").html(html1);
					
					$.each($("#loanNotice input[name=filesUuid]"), function(){
						var $this = $(this);
						$.each($(this).val().split(","), function() {
							var _this = this;
							if ($.trim(_this) != "") {
//								var str = '<div class="showProductIntroDiv"><a target="_blank" class="mas" fileUuid="' + _this + '" href="/finance/api/v1.0/downloadFile.file?fileUuid=' + _this + '" class="showProductIntro">' + tools.inquireFile(_this) + '</a>&nbsp;&nbsp;&nbsp;&nbsp;</div>'
								var str = '<div class="showProductIntroDiv"><a target="_blank" class="mas" fileUuid="' + _this + '" href="/finance/api/v1.0/viewPdfFile.json?fileUuid=' + _this + '" class="showProductIntro">' + tools.inquireFile(_this) + '</a>&nbsp;&nbsp;&nbsp;&nbsp;</div>'
								$this.parent().find("label").before(str);
							}
						});
					});
					
					var tpl2 = $("#loanNotice .loanV").html();
					var html2 = juicer(tpl2, data);
					$("#loanNotice .loanVV").html(html2);
					
					if (data.datas[0].productType == 4) {
						var tpl1 = $("#loanNotice .loan_table1 script").html();
						var html1 = juicer(tpl1, data.datas[0]);
						$("#loanNotice .loan_table1").html(html1);
						$("#loanNotice .loan_table1").before("<h1 style='margin-left:15px;font-size:16px;font-weight:bold;'>发票信息</h1>");
						$("#loanNotice .sp").html("结算价");
						$("#loanNotice .bt").addClass("none");
					}
					
					$.each($(".financeValuations"), function(i, val) {
						var financeValuations = 0;
						$.each($(this).parents("tr").find(".financeValuation"), function(i, val) {
							financeValuations = financeValuations + parseFloat($(this).html());
						});
						$(this).html(financeValuations);
						$(".financeValuations1").html(tools.formatCurrency(financeValuations));
					});
					//货箱总估值
					$.each($(".bulkstockValuations"), function(i, val) {
						var bulkstockValuations = 0;
						$.each($(this).parents("tr").find(".bulkstockValuation"), function(i, val) {
							bulkstockValuations = bulkstockValuations + parseFloat($(this).html());
						});
						$(this).html(bulkstockValuations);
					});
					if (type == "approve") {
						databind.enableInput($("#loanNotice"));
//						$(".dialogBtn").removeClass("none");
						$(".multistageAudit").attr("action", "saveLoanNoticeAudit");
					} else {
						databind.disableInput($("#loanNotice"));
						$(".button-submit").remove();
					}
					
					var fileUuids = $("#loanNotice .fileUuids").val().split(',');
					$.each(fileUuids, function() {
						var _this = this;
						if ($.trim(_this) != "") {
							var str = '<div class="showloanIntroDiv"><a target="_blank" class="mas showloanIntro" id="' + _this + '" href="/finance/api/v1.0/downloadFile.file?fileUuid=' + _this + '">' + tools.inquireFile(_this) + '</a></div>';
							$("#loanNotice .loan_info4").append(str);
						}
					});
					
					$("#loanNotice .detail").unbind("click").click(function(){
						var $this = $(this);
						if (data.datas[0].productType == 3 || data.datas[0].productType == 5 || data.datas[0].productType == 6){
//							router.route("main/wareHouseDetail.html?caseNumber=R-SH002-1706010008&financeNumber=" + $this.parents("tr").attr("financeNumber"));
							router.route("main/wareHouseDetail.html?caseNumber=" + $this.parents("tr").attr("caseNumber") + "&financeNumber=" + $this.parents("tr").attr("financeNumber"));
						} else {
							router.route("bulkstockTallyDetail/bulkstockTallyDetail.html?inventoryId=" + $this.parents("tr").attr("inventoryId"));
						}
						
					});
					
					$(".businessAuditState").val(data.datas[0].businessAuditState + "");
					$(".businessAudit").val(data.datas[0].businessAudit);
					$(".operationAuditState").val(data.datas[0].operationAuditState + "");
					$(".operationAudit").val(data.datas[0].operationAudit);
					$(".financialAuditState").val(data.datas[0].financialAuditState + "");
					$(".financialAudit").val(data.datas[0].financialAudit);
					$(".financialLeaderAuditState").val(data.datas[0].financialLeaderAuditState + "");
					$(".financialLeaderAudit").val(data.datas[0].financialLeaderAudit);
					$(".leader2AuditState").val(data.datas[0].leader2AuditState + "");
					$(".leader2Audit").val(data.datas[0].leader2Audit);
					$(".leader1AuditState").val(data.datas[0].leader1AuditState + "");
					$(".leader1Audit").val(data.datas[0].leader1Audit);
					$(".auditState1").val(data.datas[0].auditState1 + "");
					$(".audit1").val(data.datas[0].audit1);
					$(".auditState2").val(data.datas[0].auditState2 + "");
					$(".audit2").val(data.datas[0].audit2);
					
					
					$.each($(".data"), function() {
						var $this = $(this);
						if ($.trim($this.html()) == "") {
							$this.parent().remove();
						}
					});
					
					tools.barcode($("#loanNotice .barcode"), data.datas[0].loanNoticeNumber, "code128");
					
					$("#loanNotice .loanAmountUpper").html(tools.changeMoneyToChinese($("#loanNotice input[name=loanAmount]").val()));
					
					if (data.datas[0].productType == 5) {
						var str = tools.readHTML("../main/financeApprove1_5.html");
						str = $(str).find(".supplementOpinion");
						databind.fillForm($(str), data.datas[0].financeAuditDetail);
						$(str).find(".button-submit").remove();
						databind.disableInput($(str));
						$(".auditRecord").after(str);
					} else if (data.datas[0].productType == 6) {
						var str = tools.readHTML("../main/financeApprove6.html");
						str = $(str).find(".supplementOpinion");
						databind.fillForm($(str), data.datas[0].financeAuditDetail);
						$(str).find(".button-submit").remove();
						databind.disableInput($(str));
						$(".auditRecord").after(str);
					} else {
						var str = tools.readHTML("../main/financeApprove.html");
						str = $(str).find(".supplementOpinion");
						databind.fillForm($(str), data.datas[0].financeAuditDetail);
						$(str).find(".button-submit").remove();
						databind.disableInput($(str));
						$(".auditRecord").after(str);
					}
					
					
					$.each($("#loanNotice .submitState"), function() {
						var $this = $(this);
						if ($this.val() == "true") {
							$this.parent().find(".auditInfo").after("<span style='color:red; margin-left: 15px;'>已提交</span>");
							$this.parents(".multistageAudit").find(".button-submit").remove();
						} else {
							$this.parent().find(".auditInfo").after("<span style='color:red; margin-left: 15px;'>待提交</span>");
						}
					});
					
					if (data.datas[0].productType != 1 && data.datas[0].productType != 5) {
						$("#operationAudit").remove();
					}
					
					var j;
					for (var i = 0; i <= $("#loanNotice .submitState").length; i++) {
						var $this = $($("#loanNotice .submitState")[i]);
						if ($this.val() != "true" || $this == null) {
							j = i;
							break;
						}
					}
					
					if (j != null) {
						for (j = i + 1; j <= $("#loanNotice .submitState").length; j++) {
							$($("#loanNotice .submitState")[j]).parents(".multistageAudit").find(".button-submit").remove();
						}
					}
					
					
				} else {
					base.alert(3, "信息获取失败");
				}
			}
		});
	};
	
	//拒绝放款申请
    var opposeLoanNotice = function(){
        base.fnAjax({
            action: 'opposeLoanNotice.json',
            async:false,
            oData: {
            	loanNoticeId: loanNoticeId
            },
            fnSuccess: function (data) {
                if (data.status == 200) {
                	base.alert(1, "拒绝成功");
					top.location.href = "../financing/loanNoticeList.html";
                } else {
                    base.alert(3, data.message);
                }
            }
        });
    };
	
	//权限控制
    var inquireCurrentOperationList = function(){
        base.fnAjax({
            action: 'inquireCurrentOperationList.json',
            async:false,
            fnSuccess: function (data) {
                if (data.status == 200) {
                    for(var i=0;i<data.datas.length;i++){
                        var permission = data.datas[i];
                        var permissionId = permission.permissionId;
                        $.each($("#loanNotice").find("input, .permissionLink"), function() {
                        	var $this = $(this);
                        	if($this.attr("permissionId") == permissionId){
                        		$this.removeClass("none");
                        	}
                        });
                    }
                } else {
                    base.alert(3, data.message);
                }
            }
        });
    };

	return {
		init: init
	};
});